package com.jus.player.util;

import static com.jus.player.config.AppConfig.PAY_CANCEL;
import static com.jus.player.config.AppConfig.PAY_FAILED;
import static com.jus.player.config.AppConfig.PAY_OK;
import static com.jus.player.config.AppConfig.PRODUCT_TYPE_KEY;
import static com.jus.player.util.CommonUtils.findFromSp;
import static com.jus.player.util.CommonUtils.hideLoading;
import static com.jus.player.util.CommonUtils.insertToSp;
import static com.jus.player.util.CommonUtils.showToastAsync;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ProductDetails;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.QueryProductDetailsParams;
import com.android.billingclient.api.QueryPurchasesParams;
import com.appsflyer.AFInAppEventParameterName;
import com.appsflyer.AFInAppEventType;
import com.appsflyer.AppsFlyerLib;
import com.facebook.appevents.AppEventsConstants;
import com.facebook.appevents.AppEventsLogger;
import com.google.common.collect.ImmutableList;
import com.jus.player.R;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.config.AppConfig;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class OptimizedGooglePay {

    private static final String TAG = "支付类【GooglePay】";
    //连接BillingClient最大重试次数
    private static final int MAX_RETRY_COUNT = 5;
    private static final int RETRY_INTERVAL_MS = 1000;
    private final Activity activity;
    // 使用AtomicBoolean管理支付状态
    private static final AtomicBoolean isPaying = new AtomicBoolean(false);
    //记录连接BillingClient重试次数
    private static final AtomicInteger retryCount = new AtomicInteger(0);
    private final ExecutorService billingExecutor = Executors.newSingleThreadExecutor();
    /*延时重试连接BillingClient*/
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());
    private static final Handler backHandler = new Handler(Looper.getMainLooper());
    private BillingClient instance;
    private static GooglePayCallback payCallback;
    private static String currentOrderId;
    private String currentProductId;
    private static String productType;
    private static final Map<String, ProductDetails> productCache = new ConcurrentHashMap<>();

    public OptimizedGooglePay(Activity activity) {
        this.activity = activity;
        initBillingClient();
    }

    private void initBillingClient() {
        Log.e(TAG, "初始化：initBillingClient()");
        instance = BillingClient.newBuilder(activity)
                .enablePendingPurchases()
                .setListener(this::onPurchasesUpdated)
                .build();

        connectToBillingService();
    }

    /**
     * 主动支付的支付入口方法
     *
     * @param orderId   订单号
     * @param productId 商品ID
     */
    public void pay(String orderId, String productId) {
        //获取当前登陆用户邮箱
        String mEmail = findFromSp(activity, AppConfig.GOOGLE_LOGIN);
        mEmail = StringUtils.isEmpty(mEmail) ? findFromSp(activity, AppConfig.FACE_BOOK_LOGIN) : mEmail;
        if (StringUtils.isEmpty(mEmail)) {
            // 没有google登陆，跳转到登陆
            Log.e("充值页面", "充值没用GOOGLE登陆，跳转到登陆页");
            CommonUtils.logout(activity);
            showToastAsync(activity, activity.getString(R.string.check_recharge));
            return;
        }
        if (!isPaying.compareAndSet(false, true)) {
            notifyPaymentResult(PAY_FAILED, orderId, "其他支付正在进行");
            return;
        }
        try {
            currentOrderId = orderId;
            currentProductId = productId;
            // 确定商品类型
            productType = productId.contains("vip_") ?
                    BillingClient.ProductType.SUBS : BillingClient.ProductType.INAPP;
            //保存商品类型
            insertToSp(activity, PRODUCT_TYPE_KEY, productType);
            if (instance.isReady()) {
                queryProductDetails();
            } else {
                initBillingClient();
            }
        } catch (Exception e) {
            isPaying.set(false);
            notifyPaymentResult(PAY_FAILED, orderId, "Payment initialization failed");
        }
    }

    private void connectToBillingService() {
        instance.startConnection(new BillingClientStateListener() {
            @Override
            public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                    Log.d(TAG, "Billing service 已连接");
                    checkPendingPurchases();
                } else {
                    retryConnection();
                }
            }

            @Override
            public void onBillingServiceDisconnected() {
                retryConnection();
            }
        });
    }

    private void retryConnection() {
        if (retryCount.getAndIncrement() < MAX_RETRY_COUNT) {
            mainHandler.postDelayed(this::connectToBillingService, RETRY_INTERVAL_MS);
        } else {
            Log.e(TAG, "计费服务连接达到的最大重试计数：" + MAX_RETRY_COUNT);
            retryCount.set(0);
            destroy();
            showToastAsync(activity, "BillingClient连接失败");
        }
    }

    /**
     * 查询商品信息
     */
    private void queryProductDetails() {

        // 先检查缓存
        if (productCache.containsKey(currentProductId)) {
            launchBillingFlow(productCache.get(currentProductId));
            return;
        }
        QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder()
                .setProductList(ImmutableList.of(
                        QueryProductDetailsParams.Product.newBuilder()
                                .setProductId(currentProductId)
                                .setProductType(productType)
                                .build()
                )).build();
        instance.queryProductDetailsAsync(params, (billingResult, productDetailsList) -> {
            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK
                    && !productDetailsList.isEmpty()) {
                Log.e(TAG, "查询商品详情：" + productDetailsList);
                ProductDetails productDetails = productDetailsList.get(0);
                productCache.put(currentProductId, productDetails);
                launchBillingFlow(productDetails);
            } else {
                isPaying.set(false);
                notifyPaymentResult(PAY_FAILED, currentOrderId,
                        "商品查询失败: " + billingResult.getDebugMessage());
            }
        });
    }


    /**
     * 根据产品ID查询对应的商品信息
     *
     * @param productId 产品ID
     */

    public void queryProductPrice(String productId, OkHttpHelper.HttpCallback callback) {

        AtomicInteger retryCount = new AtomicInteger(0);
        Runnable retryRunnable = new Runnable() {
            @Override
            public void run() {
                if (instance.isReady()) {
                    mainHandler.post(() -> {
                        String type = productId.contains("vip_") ?
                                BillingClient.ProductType.SUBS : BillingClient.ProductType.INAPP;
                        QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder()
                                .setProductList(ImmutableList.of(
                                        QueryProductDetailsParams.Product.newBuilder()
                                                .setProductId(productId)
                                                .setProductType(type)
                                                .build())
                                ).build();
                        instance.queryProductDetailsAsync(params, (billingResult, productDetailsList) -> {
                            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                                for (ProductDetails product : productDetailsList) {
                                    // 获取本地化价格信息
                                    String formattedPrice;
                                    String currencyCode;
                                    if (BillingClient.ProductType.SUBS.equals(type)) {
                                        formattedPrice = product.getSubscriptionOfferDetails().get(0).getPricingPhases().getPricingPhaseList().get(0).getFormattedPrice();
                                    } else {
                                        formattedPrice = product.getOneTimePurchaseOfferDetails().getFormattedPrice();
                                        currencyCode = product.getOneTimePurchaseOfferDetails().getPriceCurrencyCode();
                                    }
                                    // 使用这些信息更新UI
                                    callback.onSuccess(formattedPrice);
                                }
                            }
                        });
                    });
                    return;
                }
                if (retryCount.incrementAndGet() >= 20) {
                    mainHandler.post(() -> {
                        callback.onFailure(new OkHttpHelper.HttpException(500, "BillingClient 初始化失败"));
                    });
                    return;
                }
                backHandler.postDelayed(this, 200);
            }
        };
        backHandler.post(retryRunnable);
    }

    /**
     * 弹出支付弹窗，拉起支付
     *
     * @param productDetails 商品详情
     */
    private void launchBillingFlow(ProductDetails productDetails) {
        Log.d(TAG, "开始购买产品: 产品信息 = [" + productDetails + "]");
        BillingFlowParams.ProductDetailsParams.Builder builder = BillingFlowParams
                .ProductDetailsParams.newBuilder()
                .setProductDetails(productDetails);

        // 处理订阅优惠
        if (productType.equals(BillingClient.ProductType.SUBS)
                && productDetails.getSubscriptionOfferDetails() != null
                && !productDetails.getSubscriptionOfferDetails().isEmpty()) {
            builder.setOfferToken(productDetails.getSubscriptionOfferDetails().get(0).getOfferToken());
        }

        // 计费参数
        BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                .setProductDetailsParamsList(ImmutableList.of(builder.build()))
                .build();

        BillingResult result = instance.launchBillingFlow(activity, flowParams);
        if (result.getResponseCode() != BillingClient.BillingResponseCode.OK) {
            isPaying.set(false);
            notifyPaymentResult(PAY_FAILED, currentOrderId,
                    "启动计费流程失败: " + result.getDebugMessage());
        }
    }


    /**
     * 交易监听器：更新交易状态
     *
     * @param billingResult 支付结果
     * @param purchases     交易
     */
    private void onPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases) {
        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchases != null) {
            for (Purchase purchase : purchases) {
                if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
                    handlePurchase(purchase);
                }
            }
        } else {
            isPaying.set(false);
            notifyPaymentResult(
                    billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED
                            ? PAY_CANCEL : PAY_FAILED,
                    currentOrderId,
                    billingResult.getDebugMessage()
            );
        }
    }

    /**
     * 处理交易
     *
     * @param purchase 交易
     */
    private void handlePurchase(Purchase purchase) {
        if (productType.equals(BillingClient.ProductType.INAPP)) {
            consumePurchase(purchase);
        } else {
            acknowledgePurchase(purchase);
        }
        // 2. 记录Facebook购买事件
        logFacebookPurchaseEvent(purchase);

        // 3. 记录AppsFlyer购买事件
        logAppsFlyerPurchaseEvent(purchase);
    }

    private void logFacebookPurchaseEvent(Purchase purchase) {
        AppConfig.ProductInfo product = AppConfig.ProductInfo.getInstanceById(currentProductId);
        if (product == null) {
            return;
        }
        Bundle params = new Bundle();
        // 设置货币类型(必须)
        params.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "USD");
        // 设置购买金额(必须)
        params.putDouble("value", product.getPrice());
        // 可选参数：商品ID
        params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, currentProductId);
        params.putString(AppEventsConstants.EVENT_PARAM_CONTENT, product.getName());
        // 可选参数：商品类型
        params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, productType);
        AppEventsLogger logger = AppEventsLogger.newLogger(activity);
        logger.logEvent(AppEventsConstants.EVENT_NAME_PURCHASED, params);//Facebook标准购买事件名称
    }

    private void logAppsFlyerPurchaseEvent(Purchase purchase) {
        AppConfig.ProductInfo product = AppConfig.ProductInfo.getInstanceById(currentProductId);
        if (product == null) {
            return;
        }
        Map<String, Object> eventValues = new HashMap<>();
        // 设置收入金额(必须)
        eventValues.put(AFInAppEventParameterName.REVENUE, product.getPrice());
        // 设置货币类型(必须)
        eventValues.put(AFInAppEventParameterName.CURRENCY, "USD");
        // 商品ID(推荐)
        eventValues.put(AFInAppEventParameterName.CONTENT_ID, currentProductId);
        // 商品类型(推荐)
        eventValues.put(AFInAppEventParameterName.CONTENT_TYPE, productType);
        // 订单ID(推荐)
        eventValues.put(AFInAppEventParameterName.ORDER_ID, purchase.getOrderId());

        AppsFlyerLib.getInstance().logEvent(
                activity,
                AFInAppEventType.PURCHASE, // 事件类型设为PURCHASE
                eventValues
        );
    }

    /**
     * 确认消费交易 核销商品
     *
     * @param purchase 交易
     */
    private void consumePurchase(Purchase purchase) {
        ConsumeParams params = ConsumeParams.newBuilder()
                .setPurchaseToken(purchase.getPurchaseToken())
                .build();

        instance.consumeAsync(params, (billingResult, purchaseToken) -> {
            isPaying.set(false);
            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                //购买成功处理逻辑
                //insertToSp(activity, LAST_ORDER_ID, currentOrderId);
                notifyPaymentResult(PAY_OK, currentOrderId, "Payment consumed successfully");
            } else {
                notifyPaymentResult(PAY_FAILED, currentOrderId,
                        "Consumed failed: " + billingResult.getDebugMessage());
            }
        });
    }

    /**
     * 订阅商品核销
     *
     * @param purchase 交易
     */
    private void acknowledgePurchase(Purchase purchase) {
        AcknowledgePurchaseParams params = AcknowledgePurchaseParams.newBuilder()
                .setPurchaseToken(purchase.getPurchaseToken())
                .build();

        instance.acknowledgePurchase(params, billingResult -> {
            isPaying.set(false);
            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                notifyPaymentResult(PAY_OK, currentOrderId, "Payment acknowledged successfully");
            } else {
                notifyPaymentResult(PAY_FAILED, currentOrderId,
                        "Acknowledge failed: " + billingResult.getDebugMessage());
            }
        });
    }

    /**
     * 检查未完成采购
     */
    public void checkPendingPurchases() {
        if (instance.isReady()) {
            instance.queryPurchasesAsync(QueryPurchasesParams.newBuilder()
                    .setProductType(BillingClient.ProductType.INAPP)
                    .build(), (result, purchases) -> {
                if (result.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                    for (Purchase purchase : purchases) {
                        // 只处理非当前正在处理的订单
                        if (!isPaying.get()) {
                            if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
                                if (!purchase.isAcknowledged()) {
                                    handlePurchase(purchase);
                                }
                            }
                        }
                    }
                }
            });

            instance.queryPurchasesAsync(QueryPurchasesParams.newBuilder()
                            .setProductType(BillingClient.ProductType.SUBS)
                            .build(), (billingResult, purchases) -> {
                        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                            for (Purchase purchase : purchases) {
                                if (!isPaying.get()) {
                                    if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
                                        if (!purchase.isAcknowledged()) {
                                            handlePurchase(purchase);
                                        }
                                    }
                                }

                            }
                        }
                    }
            );
        }
    }

    /**
     * 通知支付结果
     *
     * @param status  状态
     * @param orderId 订单号
     * @param message 信息
     */
    private static void notifyPaymentResult(int status, String orderId, String message) {
        if (payCallback != null) {
            mainHandler.post(() -> {
                String result = payCallback.onCallback(status, orderId);
                Log.e(TAG, "订单号为：" + orderId + "的支付结果：" + result + ": " + message);
            });
        }
    }

    public void setPayCallback(GooglePayCallback callback) {
        payCallback = callback;
    }

    public void destroy() {
        if (instance != null && instance.isReady()) {
            Log.e(TAG, "destroy Google Pay 连接");
            instance.endConnection();
        }
        isPaying.set(false);
        //billingExecutor.shutdown();
        mainHandler.removeCallbacksAndMessages(null);
    }

    public interface GooglePayCallback {
        String onCallback(int payStatus, String orderCode);
    }


}